import {
  Component,
  OnInit,
  Input,
  ViewChildren,
  OnDestroy
} from "@angular/core";
import { AppGlobalService } from "src/app/shared/service/app-global.service";
import { SearchListService } from "src/app/shared/service/search-list.service";
import { EventService } from "../../shared/service/event.service";
import { HttpService } from "../../shared/service/http.service";
import { AlertController } from "@ionic/angular";
@Component({
  selector: "app-py-customer-list",
  templateUrl: "./py-customer-list.component.html",
  styleUrls: ["./py-customer-list.component.scss"]
})
export class PyCustomerListComponent implements OnInit, OnDestroy {
  @Input() tagData: any; // 标签数据

  customerList = []; // 客户列表

  alphabet = []; // 字母列表

  index = "A";

  key: any;

  contactGroup = [];

  spell = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "J",
    "K",
    "M",
    "N",
    "L",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z"
  ];

  subscription: any; // 广播对象

  @ViewChildren("IonItemGroup") ionItemGroup;

  @ViewChildren("IonItem") ionItem;

  @ViewChildren("top") topDom;

  constructor(
    private appGlobalService: AppGlobalService,
    private broadcast: SearchListService,
    public eventService: EventService,
    public httpService: HttpService,
    private alert: AlertController
  ) { }

  ngOnInit() {
    // 结构调整
    this.customerList = this.formatList(this.tagData.data.data, "py");
    if (this.customerList.length > 0) {
      // 获取字母列表
      this.alphabet = this.customerList.map(v => v.title);
    }
    // 接收广播筛选条件
    this.subscription = this.broadcast.getMessage().subscribe(res => {
      if (res.type === "submit" && this.tagData.submitId === res.id) {
        this.key = res.value;
        setTimeout(() => {
          this.customerList = this.formatList(res.value.data.data, "py");
          if (this.customerList.length > 0) {
            this.alphabet = this.customerList.map(v => v.title);
          }
        }, 0);
      } else if (res.type === "filter") {
        this.key = res.value;
        setTimeout(() => {
          this.alphabet = this.ionItem._results.map(
            v => v.nativeElement.innerHTML
          );
        }, 0);
      }
    });
  }

  // 按照拼音首字母排序
  formatList = (arr, keyword) => {
    if (!arr || arr.length <= 0) {
      return [];
    }
    const newArr1 = {};
    const newArr = [];
    const reg = /\b(\w)|\s(\w)/g;
    let firstWord = arr[0][keyword].charAt(0).toUpperCase(); // 获取第一个分类字母
    arr.map(v => {
      v[keyword] = v[keyword].replace(reg, m => m.toUpperCase()); // 首字母大写
      if (firstWord === v[keyword].charAt(0)) {
        if (newArr1[firstWord]) {
          newArr1[firstWord].push(v);
        } else {
          newArr1[firstWord] = [];
          newArr1[firstWord].push(v);
        }
      } else {
        // 这里循环到这表示已经第二个字母了
        firstWord = v[keyword].charAt(0); // 设置第二字母
        if (newArr1[firstWord]) {
          newArr1[firstWord].push(v);
        } else {
          newArr1[firstWord] = [];
          newArr1[firstWord].push(v);
        }
      }
    });
    for (const key in newArr1) {
      if (newArr1.hasOwnProperty(key)) {
        newArr.push({ title: key, item: newArr1[key] });
      }
    }
    return newArr.sort((a, b) => a.title.localeCompare(b.title));
  }

  async go(obj, nickname) {
    // 发送信息
    if (obj.type === "chat") {
      const msgStr = '确定发送' + (obj.params.entranceType ? '消息' : '案例') + '给' + nickname + '吗？';
      const alert = await this.alert.create({
        message: msgStr,
        buttons: [
          {
            text: "取消",
            role: "cancel",
            cssClass: "secondary",
            handler: () => { }
          },
          {
            text: "确定",
            handler: () => {
              // 发送案例消息 add by andrew.wen
              if (
                localStorage.getItem("userId") !== "null") {
                if (obj.params.customer_id) {
                  const positionInfo = JSON.parse(
                    localStorage.getItem("position")
                  );
                  // tslint:disable-next-line:max-line-length
                  this.httpService.getImId(
                    undefined,
                    obj.params.customer_id,
                    positionInfo.code ? positionInfo.code : 4403,
                    item => {
                      const nowDate = Date.now();
                      if (obj.params.entranceType) {
                        // 发送商机消息 add by andrew.wen
                        if (localStorage.getItem('shareOppDetail')) {
                          const oppDetail = JSON.parse(localStorage.getItem('shareOppDetail'));
                          // localStorage.removeItem('shareOppDetail');
                          localStorage.setItem('onSendWebSocketMessageTag', 'true');
                          const shareFromUserId = localStorage.getItem("connUserId");
                          const message = {
                            text: oppDetail.title,
                            toId: item.toId,
                            fromId: shareFromUserId,
                            key: item.id,
                            type: 'opp',
                            rentunit: oppDetail.rentunit ? oppDetail.rentunit : '元/月',
                            opportunity_id: oppDetail.opportunity_id,
                            title: oppDetail.title,
                            imags: oppDetail.imags ? oppDetail.imags : '../../../assets/img/375x250@2x.png',
                            pluginId: oppDetail.pluginId,
                            big_district: oppDetail.big_district ? oppDetail.big_district : '',
                            district: oppDetail.district ? oppDetail.district : '',
                            area: oppDetail.area ? oppDetail.area : '',
                            industry: oppDetail.industry ? oppDetail.industry : '',
                            rent: oppDetail.rent ? oppDetail.rent : '',
                            transfer_fee: oppDetail.transfer_fee ? oppDetail.transfer_fee : '',
                            nowDate
                          };
                          this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
                          this.appGlobalService.showToast('发送成功', 2000, 'middle');
                        }
                      } else {
                        const caseDetail = JSON.parse(
                          localStorage.getItem("caseDetail")
                        );
                        console.log('msg----->caseDetail=' + JSON.stringify(caseDetail));
                        localStorage.setItem("onSendWebSocketMessageTag", "true");

                        // tslint:disable-next-line:max-line-length
                        const tmpServiceOpinion = caseDetail.stars === '5' ? '1' : caseDetail.stars === '4' ? '2' : caseDetail.stars === '3' ? '3' : caseDetail.stars === '2' ? '4' : caseDetail.stars === '1' ? '5' : caseDetail.stars === '0' ? '0' : '0';
                        const caseMsg = {
                          text: caseDetail.title,
                          toId: item.toId,
                          fromId: localStorage.getItem("connUserId"),
                          key: item.id,
                          type: "case",
                          title: caseDetail.title,
                          imags: caseDetail.imageUrl
                            ? caseDetail.imageUrl.url
                            : "assets/img/default_img.png",
                          caseType: "1",
                          district: 4403,
                          serviceDays: String(caseDetail.time).replace('天', ''),
                          serviceOpinion: tmpServiceOpinion,
                          industry: 1101,
                          link: caseDetail.link,
                          nowDate
                        };
                        this.eventService.eventEmit.emit("onSendWebSocketMessage", caseMsg);
                        this.appGlobalService.showToast(
                          "发送成功",
                          2000,
                          "middle"
                        );
                      }
                    }
                  );
                }
              }
            }
          }
        ]
      });
      await alert.present();
    } else {
      // 跳转页面
      const pageParams = {
        pageId: obj.target,
        params: obj.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(pageParams);
    }
  }

  // 跳转锚点
  selectIndex(i) {
    this.index = this.alphabet[i];
    this.ionItemGroup._results[i].nativeElement.scrollIntoView({
      behavior: "smooth"
    });
  }
  // 回到顶部
  toTop() {
    this.topDom._results[0].nativeElement.scrollIntoView({
      behavior: "smooth"
    });
  }

  ngOnDestroy(): void {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
